<?php
/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
namespace app\web\controller;
use app\common\Base;
use think\Db;
class Problem extends Base{
    /**
     * 获取问题列表
     */
    public function filter_blank($str) {
        $search = array(" ","　","\n","\r","\t");
        $replace = array("","","","","");
        return str_replace($search, $replace, $str);
    }
    public function advanced_search() {
        return $this->fetch();
    }
    
    public function searchproblem() {
        $problem = array();
        $problem['problem_id'] = $this->filter_blank(input('pid'));
        $problem['title'] = $this->filter_blank(input('title'));
        $problem['content'] = $this->filter_blank(input('content'));
        $problem['source'] = $this->filter_blank(input('source'));

        $problem['min_score'] = $this->filter_blank(input('min_score'));
        $problem['max_score'] = $this->filter_blank(input('max_score'));

        $problem['min_ac'] = $this->filter_blank(input('min_ac'));
        $problem['max_ac'] = $this->filter_blank(input('max_ac'));
        $search_sql= "defunct = 'N'";
        // dump($problem);
        // if($problem['min_score']=="0") echo "有啊";
        // dump($problem['min_score']);
        $query = ['pid' => $problem['problem_id'], 'title' => $problem['title'], 'content' => $problem['content'], 'source' => $problem['source'],'min_score'=>$problem['min_score'],'max_score'=>$problem['max_score'],'min_ac' => $problem['min_ac'],'max_ac' => $problem['max_ac'] ];
        if(!empty($problem['problem_id'])) {
            $search_sql .= " AND `problem_id` =" . $problem['problem_id'];
        }
        if(!empty($problem['min_ac'])) {
            $search_sql.=" AND `accepted` >= " .$problem['min_ac'];
        }
        if(!empty($problem['max_ac'])) {
            $search_sql .=" AND `accepted` <= " .$problem['max_ac'];
        }

        if(!empty($problem['min_score'] )) {
            $search_sql.=" AND `score` >= " .$problem['min_score'];
        }
        if(!empty($problem['max_score'] )) {
            $search_sql .=" AND `score` <= " .$problem['max_score'];
        }

        if(!empty($problem['content'])) {
            $search_sql .=" AND `description` LIKE \"%{$problem['content']}%\"";
        }
        if(!empty($problem['title'])) {
            $search_sql .= " AND `title` LIKE \"%{$problem['title']}%\"";
        }
        if(!empty($problem['source'])) {
            $search_sql .=" AND `source` LIKE \"%{$problem['source']}%\"";
        }
        // dump($search_sql);
        $list = db('problem')->where("defunct = 'N'  AND {$search_sql}")->paginate(30,false,array('query' => $query));
        $lists=$list->items();
        $result=array();
        $tag_lists = array();
        foreach ($lists as $key=>$val){
            // dump($val);
            $lists[$key]['result'] =$this->getstatus($this->user_id,$val['problem_id']);
            $tag_id = db('problem_tag_match')->where(['problem_id'=>$val['problem_id']])->field('tag_id')->select();
            foreach ($tag_id as $key => $value) {
                $tag_name = db('problem_tag')->where(['tag_id'=>$value['tag_id']])->field('tag_id,tag_name')->select();
                if(isset($tag_name[0]))
                    $tag_lists[$val['problem_id']][]=$tag_name[0];
            }
        }

        // dump($tag_lists);
        $this->assign('list',$lists);
        $this->assign('page',$list->render());  //分页
        $this->assign('tagval',0);  //
        $this->assign('tag_lists',$tag_lists); //标签列表
        return $this->fetch();
    }




    public function tag_delete() {
        if(!$this->is_login){
            return json(['result'=>1,'msg'=>'未登录']);
        }
        if(!$this->have_power(11)){
            return json(['result'=>1,'msg'=>'没有权限']);
        }
        $pid = input("post.pid");
        $tag_id = input("post.tag");
        $tag_name = db('problem_tag')->where(['tag_id'=>$tag_id])->field('tag_name')->select();
        db('problem_tag_match')->where(['problem_id'=>$pid,'tag_id'=>$tag_id])->delete();
        return json(['result'=>0,'msg'=>"分类标签".$tag_name[0]['tag_name']."删除成功~"]);
    }
    public function tag_add() {
        if(!$this->is_login){
            return json(['result'=>1,'msg'=>'未登录']);
        }
        if(!$this->have_power(11)){
            return json(['result'=>1,'msg'=>'没有权限']);
        }
        $pid = input("post.pid");
        $sum = db('problem_tag_match')->where(['problem_id'=>$pid])->count();
        if($sum==3)
                    return json(['result'=>0,'msg'=>'最多添加三个分类标签']);
        $tag_level_1 = input('post.tag_level_1');
        $tag_level_2 = input('post.tag_level_2');
        $tag_level_3 = input('post.tag_level_3');
        $tag_id=-1;
        if($tag_level_3>-1) $tag_id = $tag_level_3; 
        else if($tag_level_2>-1) $tag_id = $tag_level_2; 
        else if($tag_level_1>-1) $tag_id = $tag_level_1;

        // return json(['result'=>1,'tag_id'=>2,'msg'=>'waiting']);

        if(-1 != $tag_id) {
            $tag_tmp = db('problem_tag')->where(['tag_id'=>$tag_id])->field('tag_name')->select();
        }
        $tag_name="";
        if(isset($tag_tmp)) $tag_name = $tag_tmp[0]['tag_name'];
        if(-1 != $tag_id) {
            $find = db('problem_tag_match')->where(['problem_id'=>$pid,'tag_id'=>$tag_id])->find();
            if($find !=null) {
                return json(['result'=>1,'msg'=>'分类标签'.$tag_name.'已存在~']);
            }
            db('problem_tag_match')->insert(['problem_id'=>$pid,'tag_id'=>$tag_id]);
            return json(['result'=>0,'msg'=>"分类标签".$tag_name."插入成功~"]);
        } else
                return json(['result'=>1,'msg'=>'分类标签插入失败']);
    }
    public function get_tag1_id() {
        $tag1_id = input('post.tid');
        $tag_level_2 = db('problem_tag')->where(['tag_parent_id'=>$tag1_id])->field('tag_id,tag_name')->select();
        return json($tag_level_2);
    }
    public function get_tag2_id() {
        $tag2_id = input('post.tid');
        $tag_level_3 = db('problem_tag')->where(['tag_parent_id'=>$tag2_id])->field('tag_id,tag_name')->select();
        if(empty($tag_level_3)) {
            $tag_level_3=array(['tag_id'=>-2,'tag_name'=>"没有了"]);
        }
        return json($tag_level_3);
    }
    public function get_tag($pid)   {
        $tag_id_result=db('problem_tag_match')->where(['problem_id'=>$pid])->field('tag_id')->select();
        $have_tag_name=array();
        foreach ($tag_id_result as $key => $value) {
            $tmp_tag_name=db('problem_tag')->where(['tag_id'=>$value['tag_id']])->field('tag_name')->select();
            if(isset($tmp_tag_name[0]['tag_name']))
            {
                $have_tag_name[$key]['tag_name'] = $tmp_tag_name[0]['tag_name'];
                $have_tag_name[$key]['tag_id'] = $value['tag_id'];
            }
        }
        $this->assign('have_tag_name',$have_tag_name);
        $tag_level_1_name = db('problem_tag')->where(['tag_level'=>1])->field('tag_name,tag_id')->order('tag_id')->select();
        $tag_level_2_name=array(['tag_id'=>-2,'tag_name'=>"没有了"]);
        $tag_level_3_name=array(['tag_id'=>-2,'tag_name'=>"没有了"]);
        $this->assign('tag_level_1_name',$tag_level_1_name);
        $this->assign('tag_level_2_name',$tag_level_2_name);
        $this->assign('tag_level_3_name',$tag_level_3_name);
    }
    public function problemset(){

        $curTime=time();
        $keyword=input('get.keyword',null,'trim');
        $search_sql="(`problem_id` =".intval($keyword)." or `title` LIKE '%{$keyword}%' )";
        $list=db('problem')
                        ->field('problem_id,title,source,defunct,accepted,submit,solved,score')
                                ->where("{$search_sql}")
                                    ->order('problem_id ASC')
                                        ->paginate(null,FALSE,['query'=>['keyword'=>$keyword]]);
        $lists=$list->items();
        $result=array();
        $tag_lists = array();
        foreach ($lists as $key=>$val){
            $lists[$key]['result'] =$this->getstatus($this->user_id,$val['problem_id']);
            $tag_id = db('problem_tag_match')->where(['problem_id'=>$val['problem_id']])->field('tag_id')->select();
            foreach ($tag_id as $key => $value) {
                $tag_name = db('problem_tag')->where(['tag_id'=>$value['tag_id']])->field('tag_id,tag_name')->select();
                if(isset($tag_name[0]))
                                $tag_lists[$val['problem_id']][]=$tag_name[0];
            }
        }
        $this->assign('tag_lists',$tag_lists); //标签列表
        // dump($lists);
        $this->assign('list',$lists); //问题列表
        $this->assign('keyword',$keyword); //搜索关键字
        $this->assign('page',$list->render());  //分页
        $this->assign('tagval',0);  //
        $this->assign('power',$this->have_power(1));

        return $this->fetch();
    }
    //根据 user_id 获取 该用户的某一道题目通过的状态;
    // 返回状态 0 --- ac ;
    //         1 --- 尝试过
    //         2 --- 未尝试
    public function getstatus($user_id,$pid){
        if(!$this->is_login){
            return 2;
        }
        $condition['user_id']=$user_id;
        $condition['problem_id']=$pid;
        $condition['result']=4;
        $condition['contest_id']=NULL;
        $ac_res=db('solution')->where($condition)->find();
        if(!empty($ac_res)){
            return 0;
        } else {
            $condition2['user_id']=$user_id;
            $condition2['problem_id']=$pid;
            $condition2['contest_id']=NULL;
            $at_res=db('solution')->where($condition2)->find();
            if(!empty($at_res)){
                return 1;
            } else {
                return 2;
            }
        }
    }
    public function problem(){
        $pid = input('pid',0,'intval');
        $this->get_tag($pid);
        if($pid<=0){
            $this->error_ui("该题目不存在",-1);
            return ;
        }
        if($this->have_power(1))
            $res=db('problem')->where(['problem_id'=>$pid])->find();
        else
            $res=db('problem')->where(['defunct'=>'N','problem_id'=>$pid])->find();
        if(empty($res)){
            $this->error_ui("题目不存在或尚未公开",-1);
            return ;
        }
        $do_what=FALSE;
        if($this->is_login){
            $do_what=TRUE;
        }
        $this->assign('is_login',$do_what);
        $this->assign('have_power_0', $this->have_power(0));
        $this->assign('problemitem',$res);
        $this->assign('nyoj_pid',$pid);
        $this->assign('navid',1);
        $this->assign('coderank',true);
        return $this->fetch();
    }
    private function get_last_lang($userid){
        $condition['user_id']=$userid;
        $res=db('users')->where($condition)->find();
        if(empty($res)) {
            return false;
        } else {
            return $res['language'];
        }
    }
    private function get_status_data(){
        $pid= input('get.pid',0,'intval');
        $userid= input('get.userid','','trim');
        $result= input('get.result',-1,'intval');
        $language= input('get.language',-1,'intval');
        $res=array();
        if($pid!=0){
            $res['problem_id']=$pid;
        }
        if($userid!=''){
            $res['user_id']=$userid;
        }
        if($result!=-1){
            $res['result']=$result;
        }
        if($language!=-1){
            $res['language']=$language;
        }
        return $res;
    }
    public function status(){
        $data=$this->get_status_data();
        $coderank= input('coderank',null);
        $page= input('page',1);
        $rankstart=($page-1)* config('paginate.status_list_row');
        $urldata=[
                          'query'=>[
                              'pid'=> input('get.pid',0,'intval'),
                              'userid'=>input('get.userid','','trim'),
                              'result'=>input('get.result',-1,'intval'),
                              'language'=> input('get.language',-1,'intval')
                          ]
                        ];
        $data['contest_id']=null;
        $order_sql='in_date desc';
        if($coderank!=null){
            $order_sql='time ASC,memory ASC,code_length ASC';
            $data['result']=4;
            $urldata['query']['coderank']='1';
        }
        
        $list=db('solution')->where($data)->order($order_sql)->paginate(config('paginate.status_list_row'),false,$urldata);
        // dump($list->items);
        $lists = $list->items();
        // dump($lists);
        foreach ($lists as $key => $value) {
            if(empty($this->user_id)){  //如果未登录
                $is_link[$key]=false;
            } else {
                if($this->user_id == $value['user_id']) { //如果此代码是本人的
                    $is_link[$key]=true;
                } else {
                    if($this->have_power(8)) {
                        $is_link[$key]=true;//查看代码的管理员
                        continue;
                    }
                    $submit_time = db('solution_see')->where(['user_id'=>$this->user_id,'solution_id'=>$value['solution_id']])->field('time')->order('time desc')->select();
                    if(!empty($submit_time)) {
                        $submit_time = strtotime($submit_time[0]['time']);
                        if(time()-$submit_time<=604800) {
                            $is_link[$key]=true;
                            continue;
                        }
                    }
                    $is_ac = db('solution')->where(['user_id'=>$this->user_id,'problem_id'=>$value['problem_id'],'result'=>4])->field('time')->find();
                    if(empty($is_ac)) { //如果代码不是本人的，而且没有AC这个题
                        $is_link[$key]=false;
                    } else {
                        $ojcoin = db('users')->where(['user_id'=>$this->user_id])->field('ojcoin')->find();
                        $score = db('problem')->where(['problem_id'=>$value['problem_id']])->field('score')->find();
                        if($ojcoin['ojcoin']<$score['score']) {    //如果代码不是本人的，AC了这个题，但是OJ币不够
                            $is_link[$key]=false;
                        } else {    ////如果代码不是本人的，AC了这个题，OJ币充足
                            $is_link[$key]=true;
                        }
                    }
                }
            }
        }
        if(isset($is_link))
        $this->assign('is_link',$is_link);
        $this->assign('list',$list);
        $this->assign('lang',config("oj_language_list"));
        $this->assign('lang_mask', config('OJ_LANGMASK'));
        $this->assign('resultset', config('oj_result'));
        $this->assign('urldata',$data);
        $this->assign('tagval',1);
        $this->assign('coderank',$coderank==null?FALSE:TRUE);
        $this->assign('rankstart',$rankstart);
        $this->assign('nyoj_pid',input('get.pid',0,'intval'));
        $this->assign('navid',2);
        return $this->fetch();
    }
    private function get_code($cid){
        $res=db('solution')->find($cid);
        //dump($res);
        if(empty($res)) {
            return FALSE;
        } else {
            $tmp = db('source_code')->find($cid);
            $res['source']=$tmp['source'];
            return $res;
        }
    }
    private function get_error($sid){
        $res=db('compileinfo')->find($sid);
        if(empty($res)) {
            return FALSE;
        } else {
            return $res['error'];
        }
    }
    


    public function timediff($begin_time,$end_time){
        if($begin_time < $end_time){
            $starttime = $begin_time;
            $endtime = $end_time;
        }else{
            $starttime = $end_time;
            $endtime = $begin_time;
        }
        //计算天数
        $timediff = $endtime-$starttime;
        $days = intval($timediff/86400);
        //计算小时数
        $remain = $timediff%86400;
        $hours = intval($remain/3600);
        //计算分钟数
        $remain = $remain%3600;
        $mins = intval($remain/60);
        //计算秒数
        $secs = $remain%60;
        $res = array("day" => $days,"hour" => $hours,"min" => $mins,"sec" => $secs);
        return $res;
    }

    /**判断代码是否可以查看
     * 
     */

    private function judge_code($code){ //判断代码能不能看，1表示可以直接看，0表示你要询问判断，-1表示这个题你没有AC，-2表示你的硬币不够
        if($this->have_power(8)) {
            return 1;//查看代码的管理员
        }
        if($this->user_id==$code['user_id']) {
            return 1; //如果是自己的代码
        }
        if($code['contest_id']!=null){ //在比赛中的一些代码
            $info=db('contest')->find($code['contest_id']);
            $unmake_time=$info['unmake_time'];
            if($info['unmake_time']==null){
                $unmake_time=$info['end_time'];
            }
            $now=time();
            if($now> strtotime($unmake_time)&&$now> strtotime($info['end_time'])){
                return 1;
            }
        }

        $ac_problem = db('solution')->where(['user_id'=>$this->user_id,'problem_id'=>$code['problem_id'],'result'=>4])->find(); //判断这个题有没有AC
        if(empty($ac_problem)) return -1;//未AC的题目不能查看代码
        $find = db('solution_see')->where(['user_id'=>$this->user_id,'solution_id'=>$code['solution_id']])->field('time')->order('time desc')->select(); //查找表，看之前有没有看过这条记录
        if(!empty($find)) {  //如果列表当中有这条记录
            $select_time = $find[0]['time']; //查找时间
            $max_time = strtotime($select_time);
            $now = time();
            $dir_time = $now - $max_time;
            if($dir_time<=604800) { //如果这条记录是七天内的，则可以查看
                return 1;
            }
        }

        /******看OJ币够不够，不够直接返回结果-2***/
        $score = db('problem')->where(['problem_id'=>$code['problem_id']])->field('score')->find();
        $user_coin = db('users')->where(['user_id'=>$this->user_id])->field('ojcoin')->find();
        // dump($score);
        // dump($user_coin);
        if($user_coin['ojcoin']<$score['score']){
            return -2; //硬币不够，不能查看代码
        }

        return 0; //接着判断吧
    }

    public function confirm_cost_coin($code) {  //扣除相应的硬币，同时插入数据库
        $score = db('problem')->where(['problem_id'=>$code['problem_id']])->field('score')->find();
        $coin = db('users')->where(['user_id'=>$this->user_id])->field('ojcoin')->find();
        db('users')->update(['user_id'=>$this->user_id,'ojcoin'=>$coin['ojcoin']-$score['score']]);
        db('solution_see')->insert(['user_id'=>$this->user_id,'solution_id'=>$code['solution_id'],'time'=>date("Y-m-d H:i:s", time())]);
    }

    public function showcode(){
        $cid= input('cid','0','intval');
        if(!$this->is_login){
            $this->error_ui('请先登录');
        }
        $code=$this->get_code($cid);//获取提交记录以及代码
        // dump($code);
        if($code!=FALSE){//代码查到了
            
            $error= $this->get_error($cid); //获取代码的错误信息 ,编译错误信息
            $judge_code_val=$this->judge_code($code);
            // dump($judge_code_val);
            if($judge_code_val==-1) {
                $this->error_ui('这个题你还没有AC呢~');
            }  else if($judge_code_val==-2) {
                $this->error_ui('你的OJ币不够呢~');
            }  else if($judge_code_val==0) {
                // echo "result=0";
                // $score = db('problem')->where(['problem_id'=>$code['problem_id']])->field('score')->select();
                // echo '<script> if(confirm("确定要花费'.$score[0]['score'].'个OJ币来查看此代码？"))';
                // echo '{';
                // dump('你要花费OJ了');
                // echo "你要花费OJ了";
                $this->confirm_cost_coin($code);
                // echo '}';
                // echo 'else{';
                // echo 'window.history.go(-1);';
                // echo '}</script>';
                // exit();
            }
            $this->assign('code',$code);
            $this->assign('resultset', config('oj_result'));
            $this->assign('lang',config('oj_language_list'));
            $this->assign('error',$error);
            return $this->fetch();
        } else {
            //没有代码
            $this->error_ui('该代码不存在');
            return ;
        }
    }
    private function judge_problem_exist($pid=0){
        $curTime=time();
        $condition="`defunct`='N' AND problem_id = {$pid}";
        $res=db('problem')->where($condition)->find();
        if(empty($res)){
            return FALSE;
        } else {
            return TRUE;
        }
    }
    private function get_contest_num($pid,$cid){
        $condition['problem_id']=$pid;
        $condition['contest_id']=$cid;
        $res=db('contest_problem')->where($condition)->find();
        return $res['num'];
    }
    private function insert_code($pid,$lang,$code,$codelen,$cid=null){
        $data['problem_id']=$pid;
        $data['user_id']= $this->user_id;
        $data['in_date']= date("Y-m-d H:i:s",time());
        $data['language']=$lang;
        $data['ip']= request()->ip();
        $data['contest_id']=$cid;
        $data['code_length']=$codelen;
        if($cid!=null){
            $data['num']= $this->get_contest_num($pid, $cid);
        }
        $sid=db('solution')->insert($data,false,true);
        //dump($sid);
        $codedata['solution_id']=$sid;
        $codedata['source']=$code;
        db('source_code')->insert($codedata);
    }
    private function update_last_language($userid,$lang){
        $condition['user_id']=$userid;
        $data['language']=$lang;
        db('users')->where($condition)->update($data);
    }
    private function check_contest_rum($cid){
        $res=db('contest')->find($cid);
        if(empty($res)) {
            return FALSE;
        }
        $now=time();
        $start_time= strtotime($res['start_time']);
        $end_time=strtotime($res['end_time']);
        if($now<$start_time){
            //$this->error_ui('比赛尚未开始');
            return 2;
        }
        if($now>$end_time){
            //$this->error_ui('比赛已经结束,请到问题列表提交');
            return 1;
        }
        return 0;
    }
    public function do_submit(){
        $ret['code']=0;
        if(!$this->is_login){
            $ret['code']=1;
            $ret['msg']='未登录';
            return json($ret);
        }
		//黑名单
		$ban_arr=config('ban');
		if(in_array($this->user_id,$ban_arr)){
			$ret['code']=1;
            $ret['msg']='你在黑名单中,无法提交。如有疑问请联系管理员！';
            return json($ret);
		}
		//
        $pid= input('pid',0,'intval');
        $lang=input('language',0,'intval');
        $cid= input('cid',0,'intval');
        
        if(config('OJ_ENCODE_SUBMIT')){
            $code= base64_decode(input('code'));
        }
        else 
        {
            $code= input('code');
        }

        
        $codelen=strlen($code);
        if($codelen>=65000){
            $ret['code']=1;
            $ret['msg']='代码太长了';
            return json($ret);
        }
        if($codelen<5){
            $ret['code']=1;
            $ret['msg']='代码太短了';
            return json($ret);
        }
        if($cid==0){
            //普通代码提交
            if ($this->judge_problem_exist($pid)) {
                // 这里表示题目可以使用
                $this->insert_code($pid, $lang, $code,$codelen);
                $this->update_last_language($this->user_id, $lang);
                $ret['code'] = 0;
                $ret['msg'] = '提交成功';
                $ret['url'] = url('web/Problem/status');
                return json($ret);
            } else {
                $ret['code']=1;
                $ret['msg']='题目不存在或不可用';
                return json($ret);
            }
        } else {
            $status= $this->check_contest_rum($cid);
            if($status==2){
                $ret['code']=1;
                $ret['msg']='比赛尚未开始';
                return json($ret);
            } else if($status==1){
                $ret['code']=1;
                $ret['msg']='比赛已经结束,请到问题列表提交';
                return json($ret);
            } else {
                $this->insert_code($pid, $lang, $code,$codelen ,$cid);
                $this->update_last_language($this->user_id, $lang);
                $ret['code']=0;
                $ret['msg']='提交成功';
                $ret['url']=url('web/Contest/status',['cid'=>$cid]);
                return json($ret);
            }
        }
    }
    
    public function do_test(){
        $conten= input('content');
        file_put_contents('test.md', $conten);
        $this->success_ui('suceess', url('web/Problem/test'));
    }

    public function getsubmitpage(){
        $cid= input('cid',0,'intval');
        $pid= input('pid',0,'intval');
        $this->assign('cid',$cid);
        $this->assign('pid',$pid);
        $this->assign('lang_mask', config('OJ_LANGMASK'));
        $this->assign('lang_selected',$this->get_last_lang($this->user_id));
        $this->assign('lang', config('oj_language_list'));
        $this->assign('OJ_ENCODE_SUBMIT',config('OJ_ENCODE_SUBMIT')?'1':'0');
        $res['html']= $this->fetch();
        return json($res);
    }
    public function getproblemstatus(){
        $pid= input('pid',null,'intval');
        if(!$this->is_login){
            return '你还没有登录呢';
        }
        $condition['user_id']= $this->user_id;
        $condition['problem_id']=$pid;
        $res=db('solution')->where($condition)->order('in_date DESC')->limit(0,5)->select();
        $this->assign('list',$res);
        $this->assign('oj_result', config('oj_result'));
        $this->assign('oj_language_list', config('oj_language_list'));
        return $this->fetch();
    }
    public function getsubmitstatus(){
        $sid_char= input('sid',null,'trim');
        $sid=[];
        $reg='/\d+/';
        preg_match_all($reg, $sid_char, $sid);
        if($sid_char==null||empty($sid)) {
            die();
        }
        $sid=$sid[0];
       // dump($sid);
       // $res=db('solution')->where('solution_id',$sid[0])->select();
        $res=db('solution')
                //->field(['','','','','','','','',''])
                ->where(['solution_id'=>['in',$sid]])->select();
        $ret=[];
        $oj_res= config('oj_result');
        foreach($res as $k=>$v){
            if($res[$k]['contest_id']!=null){
                if($this->user_id==$res[$k]['user_id']){
                    $ret[$k]['solution_id'] = $res[$k]['solution_id'];
                    $ret[$k]['problem_id'] = $res[$k]['problem_id'];
                    $ret[$k]['user_id'] = $res[$k]['user_id'];
                    $ret[$k]['time'] = $res[$k]['time'];
                    $ret[$k]['memory'] = $res[$k]['memory'];
                    $ret[$k]['in_date'] = $res[$k]['in_date'];
                    $ret[$k]['result'] = $res[$k]['result'];
                    $ret[$k]['result_zh'] = $oj_res[$res[$k]['result']];
                    $ret[$k]['language'] = $res[$k]['language'];
                    $ret[$k]['code_length'] = $res[$k]['code_length'];
                    $ret[$k]['code'] = 0;
                    $ret[$k]['msg'] = '获取状态成功';
                }
                else {
                    $ret[$k]['code']=1;
                    $ret[$k]['msg']='比赛提交无权查看';
                }
                
            }
            else {
                $ret[$k]['solution_id'] = $res[$k]['solution_id'];
                $ret[$k]['problem_id'] = $res[$k]['problem_id'];
                $ret[$k]['user_id'] = $res[$k]['user_id'];
                $ret[$k]['time'] = $res[$k]['time'];
                $ret[$k]['memory'] = $res[$k]['memory'];
                $ret[$k]['in_date'] = $res[$k]['in_date'];
                $ret[$k]['result'] = $res[$k]['result'];
                $ret[$k]['result_zh'] = $oj_res[$res[$k]['result']];
                $ret[$k]['language'] = $res[$k]['language'];
                $ret[$k]['code_length'] = $res[$k]['code_length'];
                $ret[$k]['code']=0;
                $ret[$k]['msg']='获取状态成功';
            }
        }
        return json($ret);
    }

    public function query_code() { //返回值为查看代码是否需要OJ币
        // if(empty($this->user_id)) {
        //     return json(['result'=>-1]); //用户未登录
        // }
        /*
        http://oj.nyist.me/web/problem/query_code?sid=160&pid=228
        */
        $query_history['solution_id']=input('post.sid');
        $query_history['user_id']=$this->user_id;
        $find = db('solution')->where($query_history)->find();
        if(!empty($find)||$this->have_power(8)) //如果是是自己的代码或者是拥有查看代码权限的管理员
            return json(['result'=>-1]);
        $pid = input('post.pid');
        $score = db('problem')->where(['problem_id'=>$pid])->field('score')->select();
        $msg = '查看此代码这将要花费你'.$score[0]['score'].'个OJ币哦~~之后7天内查看此代码将不会再花费你的OJ币了~~';
        $find = db('solution_see')->where($query_history)->find();
        if(empty($find)) {
            return json(['result'=>1,'msg'=>$msg]); //尚未看过此题代码，需要OJ币
        } else {
            $select_time = db('solution_see')->where($query_history)->field('time')->order('time desc')->select();
            $max_time = strtotime($select_time[0]['time']);
            $now = time();
            $dir_time = $now - $max_time;
            if($dir_time>604800) {
                return json(['result'=>1,'msg'=>$msg,'max_time'=>strtotime($max_time[0]['time']),'now'=>$now]);//7天前看的此题代码，需要OJ币
            } else {
                $msg = '您还可以免费查看此代码';
                $time = $this->timediff($now-604800,$max_time);
                $msg.=$time['day']."天".$time['hour']."小时".$time['min']."分钟".$time['sec']."秒~";
                return json(['result'=>0,'msg'=>$msg]);  //花费oj币查看代码
            }
        }

    }

    public function cost_code() {
        $query_history['solution_id']=input('post.sid');
        $query_history['user_id']=$this->user_id;
        $pid = input('post.pid');
        $score = db('problem')->where(['problem_id'=>$pid])->field('score')->find();
        $coin = db('users')->where(['user_id'=>$this->user_id])->field('ojcoin')->find();
        db('users')->update(['user_id'=>$this->user_id,'ojcoin'=>($coin['ojcoin']-$score['score'])]);
        db('solution_see')->insert(['user_id'=>$this->user_id,'solution_id'=>$query_history['solution_id'],'time'=>date("Y-m-d H:i:s", time())]);
        return json(['res'=>true]);
    }
    
}
